// 准备 Prisma 运行时：
// - 在 pnpm 布局下，.prisma 位于 node_modules/.pnpm/@prisma+client@*/node_modules/.prisma
// - Prisma 客户端在运行时 require('.prisma/client/default')
// - 为了让 electron-builder 能正确打包并在运行时找到模块，需要把该目录复制到 node_modules/.prisma/

import { access, cp, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import process from 'node:process'

async function exists(path) {
  try {
    await access(path)
    return true
  }
  catch {
    return false
  }
}

async function findPnpmPrismaClientRoot() {
  const base = join(process.cwd(), 'node_modules', '.pnpm')
  const { readdir, stat } = await import('node:fs/promises')
  try {
    const entries = await readdir(base)
    for (const name of entries) {
      if (name.startsWith('@prisma+client@')) {
        const full = join(base, name, 'node_modules', '.prisma', 'client')
        try {
          const st = await stat(full)
          if (st && st.isDirectory())
            return full
        }
        catch {}
      }
    }
  }
  catch {}
  return ''
}

async function main() {
  const target = join(process.cwd(), 'node_modules', '.prisma', 'client')
  const source = await findPnpmPrismaClientRoot()
  if (!source) {
    console.warn('[prepare-prisma-binaries] 未找到 pnpm 的 .prisma/client 源目录，可能已经存在或未安装 @prisma/client')
    return
  }

  if (!(await exists(target)))
    await mkdir(target, { recursive: true })

  await cp(source, target, { recursive: true })
  console.log(`[prepare-prisma-binaries] 已复制 Prisma 客户端: ${source} -> ${target}`)

  // 额外：为运行时相对解析创建嵌套路径 node_modules/@prisma/client/.prisma/client
  try {
    const nestedRoot = join(process.cwd(), 'node_modules', '@prisma', 'client', '.prisma')
    const nestedTarget = join(nestedRoot, 'client')
    if (!(await exists(nestedTarget)))
      await mkdir(nestedTarget, { recursive: true })
    await cp(source, nestedTarget, { recursive: true })
    console.log(`[prepare-prisma-binaries] 已同步 Prisma 客户端到嵌套路径: ${source} -> ${nestedTarget}`)
  }
  catch (err) {
    console.warn('[prepare-prisma-binaries] 同步到 @prisma/client/.prisma 失败（可忽略）:', err?.message || String(err))
  }
}

main().catch((err) => {
  console.error('[prepare-prisma-binaries] 失败:', err)
  process.exit(1)
})
